// store/user.js

import axios from "axios";
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { apiPostSign, apiGetUserData, apiReviseUserData } from "@/api/api";
import router from "@/router/index";

// 创建 store
const useUserStore = defineStore("user", {
  //持久化
  persist: true,
  // 定义状态：一个函数，返回一个对象
  state: () => ({
    token: "",
    username: "",
    name: "雷猴",
    userData: {
      //存储登录用户信息
      id: 0, //用户ID
      niceName: "", //生成链接
      name: "", //昵称
      url: "", //自定义网站地址
      description: "", //个人说明
      link: "", //用户连接
      slug: "", //用户的字母数字标识符。
      email: "", //邮件地址
      avatar: {}, //头像
    },
  }),

  // 定义 getters，等同于组件的计算属性
  getters: {
    // getter 函数接收 state 作为参数，推荐使用箭头函数
    hello: (state) => "Hello!" + state.username,
    fullName: (state) => {
      return "我叫 " + state.name;
    },
  },

  // 定义 actions，有同步和异步两种类型
  actions: {
    /**
     * 登录
     * 传入用户名和密码对象，进行登录
     */
    async userLogin(data: { username: string; password: string }) {
      apiPostSign({
        username: data.username,
        password: data.password,
      })
        .then((res) => {
          ({
            token: this.token,
            user_display_name: this.userData.name,
            user_email: this.userData.email,
            user_nicename: this.userData.niceName,
          } = res.data);
          //成功登录后跳转至用户页
          router.push("/user");
          //拿到数据啦
          console.log("res拿到的值：");
          console.log(res);
          //登录成功，通过token获取登录用户详细信息，保存到Pinia
          this.getUserData();
        })
        .catch((error) => {
          console.log("捕获错误信息");
          console.log(error);
          let message = "";
          if (error && error.status === 403) {
            console.log(message);
            message = error.data.message;
          } else {
            message = "登录过期，请重新登录";
            router.push("/expore");
          }
          ElMessage({
            message: message,
            type: "error",
            offset: 150,
            grouping: true,
            showClose: true,
            dangerouslyUseHTMLString: true,
          });
        });
    },
    /**
     * 登录成功后，获取当前登录用户信息，存入store，持久化保存
     * @param userData
     */
    getUserData() {
      console.log("我执行了11");
      apiGetUserData({})
        .then((res) => {
          ({
            id: this.userData.id,
            avatar_urls: this.userData.avatar,
            url: this.userData.url,
            description: this.userData.description,
            link: this.userData.link,
            slug: this.userData.slug,
          } = res);
        })
        .catch((error) => {
          alert("获取失败");
          console.log(error);
        });
    },

    /**
     * 修改用户信息
     * 提供用户ID和修改内容
     * @param id
     * @param obj
     */
    apiReviseUser(
      id: number,
      obj: { name: string; url: string; description: string; email: string }
    ) {
      //修改信息推送到站点
      apiReviseUserData(id, obj)
        .then((res) => {
          alert("修改成功");
          //更新store信息
          console.log("拿到的值：" + res);
          console.log(obj);

          this.userData.name = obj.name;
          this.userData.url = obj.url;
          this.userData.description = obj.description;
          this.userData.email = obj.email;
        })
        .catch((error) => {
          alert("修改失败");
        });
    },

    //注销操作
    commitInfo() {
      //清空数据
      this.$reset();
      //跳转至首页
      router.push("/");
    },
  },
});

export default useUserStore;
